<!--
编辑用户
 -->
<template>
  <div class='app-container paddingT50'>
    <div class='paddingLR20 clearfix'>
      <el-card shadow='never' class='oper-btn-card'>
        <div class='clearfix'>
          <div class='fl'>
            <el-button type='primary' size='medium' :loading='btnLoading.save' @click='btnSaveData'>保存</el-button>
            <el-button type='default' size='medium' @click='btnCancle'>取消</el-button>
          </div>
        </div>
      </el-card>
    </div>
    <el-card shadow='never' class='border-radius-none margin-t2'>
      <!-- dataObj: {{ dataObj }} -->
      <el-form
        ref='form'
        :model='formData'
        :rules='rules'
        label-position='right'
        label-width='100px'
        size='mini'
      >
        <h3>基础信息</h3>
        <el-divider/>
        <div class='paddingTb20 w600'>
          <el-form-item :label='`真实姓名:`' prop='realName'>
            <el-input v-model='formData.realName' maxlength="20" show-word-limit/>
          </el-form-item>
          <el-form-item :label='`联系电话:`' prop='phone'>
            <el-input v-model='formData.phone' maxlength="11" show-word-limit/>
          </el-form-item>
          <el-form-item :label='`身份证号:`' prop='idcard'>
            <el-input v-model='formData.idcard' maxlength="18" show-word-limit/>
          </el-form-item>
          <el-form-item label='民族:' prop='nation'>
            <el-select
              v-model='formData.nation'
              filterable
              remote
              reserve-keyword
              placeholder='民族'
              :remote-method='remoteMethod'
              :loading='appLoading'
            >
              <el-option
                v-for='item in nationOptions'
                :key='item.value'
                :label='item.label'
                :value='item.value'
              />
            </el-select>
          </el-form-item>
          <el-form-item :label='`职业:`' prop='duty'>
            <el-input v-model='formData.duty' maxlength="40" show-word-limit/>
          </el-form-item>
          <el-form-item :label='`住址:`' prop='address'>
            <el-input v-model='formData.address' maxlength="64" show-word-limit/>
          </el-form-item>
          <el-form-item :label='`人脸:`'>
            <el-upload
              action=''
              :show-file-list='false'
              :on-success='handleAvatarSuccess'
              :before-upload='beforeAvatarUpload'
              :http-request='requestUpload'
            >
              <img v-if='imageUrl' :src='imageUrl' class='avatar'>
              <i v-else class='el-icon-plus avatar-uploader-icon'/>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import { create, update, findById } from '@/api/user/user.js'
import { default as defaultConfig } from '@/config/index.js'

import { upload } from '../../../api/common/fileupload'

export default {
  label: 'SysUserAdd',
  mixins: [oftenuse],
  props: {
    operation: {
      type: String,
      default: null,
      validator: (value) => {
        return ['add', 'update'].indexOf(value) !== -1
      }
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      imageUrl: '',
      nationOptions: defaultConfig.nationOptions,
      appLoading: false,
      appLoad: false,
      formData: {
        realName: null,
        phone: null,
        idcard: null,
        duty: null,
        nation: null,
        address: null,
        face: null
      },
      originDataObj: {}, // 编辑状态初始值，用于对比是否修改
      optionsData: {},
      rules: {
        realName: [
          { required: true, message: '请输入真实名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[34578]\d{9}$/, message: '手机号格式不正确' }
        ],
        idcard: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号码格式不正确' }
        ],
        nation: [
          { required: true, message: '请选择民族', trigger: 'blur' }
        ],
        duty: [
          { required: false, message: '请输入职业', trigger: 'change' }
        ],
        address: [
          { required: false, message: '请输入地址', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    // 页面初始化数据写在这里
    this.initData()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //  覆盖默认上传行为
    requestUpload(params) {
      const fileData = new FormData()
      fileData.append('file', params.file)
      fileData.append('FileName', params.file.label)
      fileData.append('async', true)
      upload(fileData).then(res => {
        if (res.data.flag) {
          this.formData.icon = res.data.result.relativePath
          this.imageUrl = URL.createObjectURL(params.file)
        }
      })
    },
    btnSaveData() {
      this.valiData().then(_ => {
        const params = this.formData
        this.setBtnLoading('save', true)
        this.saveData(params).then(_ => {
          this.setBtnLoading('save', false)
        })
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.appLoading = true
        setTimeout(() => {
          this.appLoading = false
          this.nationOptions = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.nationOptions = []
      }
    },
    jump2list() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'sysUserList',
        params: { refresh: true }
      })
    },
    btnCancle() {
      this.jump2list()
    },
    valiData() {
      const v1 = this.handleValid('form')
      return Promise.all([v1])
    },
    saveData(params) {
      this.setBtnLoading('save', true)
      if (!params.id) {
        return create(params).then(res => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) {
            this.$notify.error({ title: '保存异常！', message: res.data.message })
            return
          }
          this.$notify.success({ title: '保存成功！' })
          this.jump2list()
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err.message })
        })
      } else {
        return update(params).then(res => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) {
            this.$notify.error({ title: '修改异常！', message: res.data.message })
            return
          }
          this.$notify.success({ title: '修改成功！' })
          this.jump2list()
        }).catch(err => {
          this.$notify.error({ title: '修改异常！', message: err.message })
        })
      }
    },
    findById(id) {
      findById({ id: id }).then(res => {
        if (res.data.flag) {
          this.formData = res.data.result
        } else {
          this.$notify.error({ title: '查询失败!', message: res.data.message })
        }
      })
    },
    initData() { // 初始化数据
      console.log('初始化数据')
      this.initOptionsData()
      const id = this.id
      if (id) {
        // 初始化修改时的数据
        this.initUpdateData(id)
      }
    },
    initUpdateData(id) {
      this.findById(id)
    },
    initOptionsData() {
    }
  }
}
</script>

<style scoped>
.el-divider--horizontal {
  margin: 5px 0;
}
</style>
